<template>
  <div>
    <basic-page-vxe
      ref="basePage"
      list-api="querySysOrg"
      del-api="deleteSysOrg"
      export-api="exportSysOrg"
      :export-name="$route.meta.title"
      :search-form="basicData.searchForm"
      :search-handle="basicData.searchHandle"
      :columns="basicData.columns"
      :show-pagination="false"
      :is-tree-data="true"
    />
    <!--新增-->
    <el-dialog :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="1100px">
      <el-form ref="dataForm" :rules="rules" :model="temp" :inline="true" label-position="right" label-width="120px" style="width: 100%">
        <el-form-item label="机构名称" prop="orgName">
          <el-input v-model="temp.orgName" style="width: 360px" placeholder="请输入" maxlength="32" clearable />
        </el-form-item>
        <el-form-item label="机构类型" prop="orgType">
          <el-select v-model="temp.orgType" style="width: 360px" placeholder="请选择" :disabled="temp.parentId !== '' || dialogStatus === 'update'">
            <el-option
              v-for="item in orgOptions"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="机构描述" prop="orgDescription">
          <el-input v-model="temp.orgDescription" style="width: 360px" placeholder="请输入" maxlength="32" clearable />
        </el-form-item>
        <el-form-item label="排序" prop="orgSequence">
          <el-input-number v-model="temp.orgSequence" placeholder="请输入" style="width: 360px" maxlength="32" clearable />
        </el-form-item>
        <el-form-item label="上级菜单" prop="parentId">
          <el-tooltip content="如不选择默认为根节点" placement="bottom" effect="light">
            <el-select ref="selectParentId" v-model="temp.parentId" placeholder="请选择" style="width: 100%" clearable @clear="handleClearParentId">
              <el-option :key="temp.parentId" hidden :value="temp.parentId" :label="parentName" />
              <el-tree ref="treeParentId" node-key="id" :data="parentIdOptions" :props="{label: 'title'}" :expand-on-click-node="false" :check-on-click-node="true" @node-click="handleNodeClickParentId" />
            </el-select>
          </el-tooltip>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { querySysOrgTree, getSysDictByType, addSysOrg, updateSysOrg } from '@/api/admin'
export default {
  name: '',
  components: {},
  directives: {},
  filters: {},
  data() {
    return {
      basicData: {
        columns: [
          { config: { title: '机构名称', field: 'orgName' }, type: 'tree' },
          { config: { title: '机构类型', field: 'orgTypeCn', width: '140' }},
          { config: { title: '机构描述', field: 'orgDescription' }, type: 'copy' },
          { config: { title: '排序', field: 'orgSequence', width: '80' }},
          { config: { title: '操作', field: 'opt', width: '180' }, type: 'render',
            render: (h, scope) => {
              return (
                <div>
                  <el-button plain size='mini' type='primary' v-permission="'update'" onClick={() => this.handleUpdate(scope.row)}><i class='el-icon-edit'></i> 编辑</el-button>
                  <el-button plain size='mini' type='danger' v-permission="'delete'" onClick={() => this.$refs.basePage.handleDelete(scope.row)}><i class='el-icon-delete'></i> 删除</el-button>
                </div>
              )
            }
          }
        ],
        searchForm: [
          { type: 'Input', label: '机构名称', prop: 'orgName', width: '180px' },
          { type: 'Select', label: '机构类型', prop: 'orgType', width: '180px', options: [] },
          { type: 'Input', label: '机构描述', prop: 'orgDescription', width: '180px', options: [] }
        ],
        searchHandle: [
          { label: '新增', type: 'success', icon: 'el-icon-plus', permission: 'add', handle: () => { this.handleCreate() } }
        ]

      },
      parentName: '',
      parentIdOptions: [],
      orgOptions: [],
      temp: {
        id: undefined,
        parentId: '',
        prjmgtType: '',
        orgName: '',
        orgType: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        orgName: [{ required: true, message: '请输入机构名称！', trigger: ['blur', 'change'] },
          { min: 3, max: 100, message: '长度在 3 到 100 个字符', trigger: 'blur' }],
        orgType: [{ required: true, message: '请选择机构类型！', trigger: 'change' }]
      }
    }
  },
  computed: {},
  created() {
    this.getType()
  },
  mounted() {
  },
  methods: {
    // 业务逻辑
    getType() {
      getSysDictByType('org').then(response => {
        this.orgOptions = response.data
        this.basicData.searchForm[1].options = response.data
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        parentId: '',
        prjmgtType: ''
      }
    },
    handleNodeClickParentId(data) {
      this.parentName = data.title
      this.temp.parentId = data.id
      this.$refs.selectParentId.blur()
      this.validateParentId()
    },
    // 新增
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      querySysOrgTree().then(response => {
        this.parentIdOptions = response.data.list
      })
    },
    createData() {
      if (this.$refs.selectParentId.value) {
        this.validateParentId()
      }
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.temp.parentId === '') {
            this.temp.parentId = '0'
          }
          addSysOrg(this.temp).then(response => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '新增成功',
              type: 'success',
              duration: 2000
            })
            this.handleReset()
          })
        }
      })
    },
    // 编辑
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        if (this.temp.parentId === '0') {
          this.temp.parentId = ''
        }
      })
      querySysOrgTree().then(response => {
        this.parentIdOptions = response.data.list
      })
    },
    updateData() {
      if (this.$refs.selectParentId.value) {
        this.validateParentId()
      }
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // const tempData = Object.assign({}, this.temp)
          const tempData = Object.assign({}, this.temp)
          delete tempData.children
          delete tempData.createTime
          tempData.parentId = this.temp.parentId ? this.temp.parentId : 0
          updateSysOrg(tempData).then(response => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '编辑成功',
              type: 'success',
              duration: 2000
            })
            this.handleReset()
          })
        }
      })
    },
    // 刷新
    handleReset() {
      this.getType()
      this.$refs.basePage.getList()
    },
    handleClearParentId() {
      this.parentName = ''
      this.temp.parentId = ''
    },
    validateParentId() {
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate('parentId')
      })
    }
  }
}
</script>

<style scoped lang="scss">
.warning{
  text-align: center;
  font-size: 20px;
}
.el-icon-info{
  font-size: 30px;
  color: orange;
}
</style>
